package fwhmc.filter;

import fdupc.http.ResultBean;
import fwhmc.utils.OutDataTools;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类描述:  全局异常拦截
 *
 * @author 王雷
 * @version 1.0.0
 * @date 2022/10/1 0001 下午 6:55
 */
@Slf4j
@Order(-1)
@Component
public class ExceptionFilterHandler implements ErrorWebExceptionHandler {

    /**
     * 功能描述：全局异常处理方法
     *
     * @date : 2022/10/6 0006 下午 8:10
     */
    @Override
    public @NotNull Mono<Void> handle(@NotNull ServerWebExchange serverWebExchange, Throwable throwable) {
        ResultBean resultBean;
        log.debug("全局异常拦截异常", throwable);
        if ("BadCredentialsException".equals(throwable.getClass().getSimpleName())) {
            resultBean = ResultBean.factoryError("用户名或密码错误");
        } else if ("DisabledException".equals(throwable.getClass().getSimpleName())) {
            resultBean = ResultBean.factoryError(throwable.getMessage());
        } else if ("ResponseStatusException".equals(throwable.getClass().getSimpleName())) {
            resultBean = ResultBean.factoryError(throwable.getMessage()).setCode(((ResponseStatusException)throwable)
                    .getRawStatusCode());
        } else {
            resultBean = ResultBean.factoryError("系统异常");
        }
        return OutDataTools.giveResultBeanWriteAndFlushWith(serverWebExchange, resultBean);
    }
}
